package com.qiantu.phone.widget;

import android.content.Context;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import com.facebook.drawee.backends.pipeline.PipelineDraweeControllerBuilder;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.fresco.animation.drawable.AnimatedDrawable2;
import com.facebook.fresco.animation.drawable.AnimationListener;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.qiantu.api.utils.ThemeUtil;
import com.qiantu.phone.BuildConfig;

import java.util.HashMap;

/**
 * Created by luzx on 2019/05/16.
 */
public class SimpleAnimationDraweeView extends SimpleDraweeView {

    private ControllerListener mControllerListener;

    private boolean canStop = false;

    private boolean startAnimation = false;

    public HashMap<String, AnimatedDrawable2> mAnimatedDrawable2Map = new HashMap<>();

//    private String staticImage;
    private String animationImageUri;

    private GenericDraweeHierarchyBuilder mGenericDraweeHierarchyBuilder;

    public SimpleAnimationDraweeView(Context context, GenericDraweeHierarchy hierarchy) {
        super(context, hierarchy);
    }

    public SimpleAnimationDraweeView(Context context) {
        super(context);
    }

    public SimpleAnimationDraweeView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SimpleAnimationDraweeView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public SimpleAnimationDraweeView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void setImageURI(String uriString) {
        if(TextUtils.isEmpty(uriString)){
            return;
        }
//        staticImage = BuildConfig.APP_SCENE_BASE + uriString;
        startAnimation = false;
        canStop = false;
        String suffix = "";
        switch (ThemeUtil.themeId){
            case ThemeUtil.THEME_DEFAULT:
                suffix = ".png";
                break;
            case ThemeUtil.THEME_BLACK_GOLD:
            case ThemeUtil.THEME_ORANGE:
                suffix = ".png";
                break;
        }
        if(uriString.contains("res:/")){
            animationImageUri = uriString;
        }else{
            if(uriString.lastIndexOf(".") > 0){
                animationImageUri = BuildConfig.APP_SCENE_BASE + ThemeUtil.getIconThemeSuffix() + uriString.substring(0, uriString.lastIndexOf(".")) + suffix;
            }else{
                animationImageUri = BuildConfig.APP_SCENE_BASE + ThemeUtil.getIconThemeSuffix() + uriString + suffix;
            }
        }
        setPlaceholderImage();
        if (mControllerListener == null) {
            mControllerListener = new BaseControllerListener<ImageInfo>() {
                @Override
                public void onFinalImageSet(String id, @Nullable ImageInfo imageInfo, @Nullable Animatable anim) {
                    if (anim != null) {
                        AnimatedDrawable2 animatedDrawable2 = (AnimatedDrawable2) anim;
                        animatedDrawable2.setAnimationListener(mAnimationListener);
                        if (startAnimation == true) {
                            animatedDrawable2.start();
                        }
                        mAnimatedDrawable2Map.put(animationImageUri, animatedDrawable2);
                    }
                }
            };
        }
//        ImageRequest lowResImageRequest = ImageRequestBuilder
//                .newBuilderWithSource(Uri.parse(animationImage))
//                .build();
        ImageRequest imageRequest = ImageRequestBuilder
                .newBuilderWithSource(Uri.parse(animationImageUri))
                .build();
        DraweeController controller = ((PipelineDraweeControllerBuilder)getControllerBuilder())
//                .setLowResImageRequest(lowResImageRequest)
                .setImageRequest(imageRequest)
                .setAutoPlayAnimations(false)
                .setControllerListener(mControllerListener)
                .setOldController(getController())
                .build();
        setController(controller);
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        if(visibility == VISIBLE){
            setPlaceholderImage();
        }
        super.onVisibilityChanged(changedView, visibility);
    }

    private void setPlaceholderImage(){
        if(mAnimatedDrawable2Map.get(animationImageUri) != null ){
            if(mGenericDraweeHierarchyBuilder == null){
                mGenericDraweeHierarchyBuilder = new GenericDraweeHierarchyBuilder(getResources());
            }
            /*设置placeholder，减少连续加载两个动图时的间隙，同时设置渐变时间为0,动态webp不会缓存到内存*/
            GenericDraweeHierarchy hierarchy = mGenericDraweeHierarchyBuilder
                    .setPlaceholderImage(mAnimatedDrawable2Map.get(animationImageUri))
                    .setFadeDuration(0)
                    .build();
            setHierarchy(hierarchy);
        }
    }

    public void setCanStop(boolean canStop) {
        this.canStop = canStop;
    }

    public void startAnimation() {
        startAnimation = true;
        if (mAnimatedDrawable2Map.get(animationImageUri) != null) {
            if(mParentClickView != null){
                mParentClickView.setEnabled(false);
            }
            mAnimatedDrawable2Map.get(animationImageUri).stop();
            mAnimatedDrawable2Map.get(animationImageUri).start();
        }
    }

    public void stopAnimation() {
        startAnimation = false;
        if (mAnimatedDrawable2Map.get(animationImageUri) != null) {
            mAnimatedDrawable2Map.get(animationImageUri).stop();
        }
    }

    private View mParentClickView;
    public void setParentClickView(View view){
        mParentClickView = view;
    }

    private AnimationListener mAnimationListener = new AnimationListener() {
        @Override
        public void onAnimationStart(AnimatedDrawable2 drawable) {
            Log.i("luzxluzx", "onAnimationStart");
        }

        @Override
        public void onAnimationStop(AnimatedDrawable2 drawable) {
            startAnimation = false;
            canStop = false;
            Log.i("luzxluzx", "onAnimationStop");
        }

        @Override
        public void onAnimationReset(AnimatedDrawable2 drawable) {
//            Log.i("luzxluzx", "onAnimationReset");
        }

        @Override
        public void onAnimationRepeat(AnimatedDrawable2 drawable) {
//            Log.i("luzxluzx", "onAnimationRepeat");
//            if (drawable.isRunning() && canStop) {
//                drawable.stop();
//            }
        }

        @Override
        public void onAnimationFrame(AnimatedDrawable2 drawable, int frameNumber) {
            if(frameNumber == drawable.getFrameCount() - 1 && drawable.isRunning() && canStop){
                drawable.stop();
                if(mParentClickView != null){
                    mParentClickView.setEnabled(true);
                }
                Log.i("luzxluzx", "onAnimationFrame frameNumber:" + frameNumber);
            }
        }
    };

    @Override
    protected void onDetachedFromWindow() {
        if(mAnimatedDrawable2Map.get(animationImageUri) != null){
            mAnimatedDrawable2Map.get(animationImageUri).stop();
        }
        super.onDetachedFromWindow();
    }
}
